package com.zxy.leetcode._00000_00099._00020_00029;

import com.zxy.leetcode.common.ListNode;
import com.zxy.leetcode.common.ListNodeHelper;

/**
 * https://leetcode-cn.com/problems/merge-two-sorted-lists/
 */
public class Test00021 {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;

        ListNode node10 = new ListNode(1);
        ListNode node11 = new ListNode(3);
        ListNode node12 = new ListNode(4);
        node10.next = node11;
        node11.next = node12;

        ListNode ret = new Test00021().mergeTwoLists(node1, node10);
        ListNodeHelper.print(ret);
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode();
        ListNode tail = head;
        while (l1 != null || l2 != null) {
            if (l1 == null) {
                tail.next = l2;
                break;
            }
            if (l2 == null) {
                tail.next = l1;
                break;
            }

            int val1 = l1.val;
            int val2 = l2.val;
            if (val1 <= val2) {
                ListNode next = l1.next;
                tail.next = l1;
                l1.next = null;
                l1 = next;
            }else {
                ListNode next = l2.next;
                tail.next = l2;
                l2.next = null;
                l2 = next;
            }
            tail = tail.next;
        }

        return head.next;
    }

}



